package com.xxxx.seckill.exception;

import com.xxxx.seckill.VO.ResponseBean;
import com.xxxx.seckill.VO.ResponseBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理类
 */
@RestControllerAdvice // 这样返回的就是一个 response body ，不用在方法上具体去返回
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseBean ExceptionHandler(Exception e) {
        if (e instanceof GlobalException ex) {
            return ResponseBean.error(ex.getResponseBeanEnum());
        } else if (e instanceof BindException ex) {
            ResponseBean responseBean = ResponseBean.error(ResponseBeanEnum.BIND_ERROR);
            responseBean.setMessage("参数校验异常：" + ex.getBindingResult().getAllErrors().getFirst().getDefaultMessage());
            return responseBean;
        } else {
            e.printStackTrace();
            return ResponseBean.error(ResponseBeanEnum.ERROR); // 抛出服务器异常500
        }
    }

}
